package com.paomi.client.activity.reply;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.paomi.client.R;
import com.paomi.client.activity.detail.adapter.TipListAdapter;
import com.paomi.client.activity.detail.model.Comment;
import com.paomi.client.activity.detail.model.TipCommentBean;
import com.paomi.client.activity.message.model.MyGetReplyList;
import com.paomi.client.activity.reply.model.ReplyContent;
import com.paomi.client.activity.reply.model.ReplyJsonBean;
import com.paomi.client.base.BaseLoadMorePresenter;
import com.paomi.client.base.BaseMvpLCEView;
import com.paomi.client.bean.BaseJSON;
import com.paomi.client.net.Api;
import com.paomi.client.net.BaseCallback;
import com.paomi.client.net.Constants;
import com.paomi.client.utils.ToastUtil;
import com.paomi.client.utils.UIUtils;
import com.paomi.client.widget.RxToast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

/**
 * Created by pc on 2018/11/9
 * Describe:
 * com.paomi.client.activity.reply
 */
public class ReplyPresenter extends BaseLoadMorePresenter<BaseMvpLCEView> {
    private List<ReplyContent> commentList = new ArrayList<>();

    private String getid;
    private String pid;
    private int pageNum;
    private Context context;

    /**
     * 请求回复列表接口
     * * pageNum	true	页码
     * * pageSize	true	页记录数
     * * sort	true	0 时间 1 点赞数
     *
     * @param goodId 商品ID
     * @param pid    被评论ID
     * @param type   mainCommentId	true	被评论ID
     *               type	true	评论归属 0 演出项目 1 衍生品 2资讯
     *               typeId	true	id
     *               pageNum	true	页码
     *               pageSize	true	页记录数
     *               sort	true	0 时间 1 点赞数
     */
    public void setReplyContent(Context context,String goodId, String pid, String type, int page) {
        this.context = context;
        getid = goodId;
        this.pid = pid;
        this.pageNum = page;
        loadData(true);
    }

    @Override
    protected void loadData(int page, int skip, boolean pullToRefresh) {
        if (getid != null) {
            Map<String, String> maps = new HashMap<>();
            maps.put("mainCommentId", pid);
            maps.put("typeId", getid);
            maps.put("pageNum", "" + pageNum);
            maps.put("pageSize", "" + Constants.PAGE_SIZE);
            maps.put("type", "0");
            maps.put("sort", "0");
            Api.getInstanceService(Constants.Ticket_URL).getReplyList(maps).enqueue(new BaseCallback<ReplyJsonBean>() {
                @Override
                public void onResponse(Call<ReplyJsonBean> call, ReplyJsonBean result) {
                    if (pageNum == 1) {
                        commentList.clear();
                    }
                    if(commentList.size()>0){
                        //判断是否有重复数据
                        boolean isData=false;
                        List<ReplyContent>  comments1=result.getReturnData().getData();
                        for(ReplyContent comment:comments1){
                            for(int i=0;i<commentList.size();i++){
                                if(comment.getId() == commentList.get(i).getId()){
                                    isData=false;
                                    break;
                                }else{
                                    isData=true;
                                }
                            }
                        }
                        if(isData){
                            commentList.addAll(result.getReturnData().getData());
                        }else{
                            ToastUtil.getToastEmail().ToastShow(context, null, 1, R.layout.toast_view, context.getResources().getString(R.string.data_null));
                        }
                    }else{
                        commentList.addAll(result.getReturnData().getData());
                    }
                    if(isViewAttached()){
                        getView().setData(commentList, false);
                    }
                    EventBus.getDefault().post(result);
                }
            });
        } else {
            getView().setData(commentList, false);
        }
    }

    /**
     * 点赞接口的调用
     */
    public void addLikeClick(boolean isClick, String id) {
        Api.getInstanceService(Constants.Ticket_URL).getaddLike(id).enqueue(new BaseCallback<BaseJSON>() {
            @Override
            public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                if (isClick) {
                    result.returnMessage = "点赞成功";
                } else {
                    result.returnMessage = "取消点赞";
                }
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        EventBus.getDefault().post(result);
                    }
                }, 100);
            }
        });

    }


    /**
     * 举报评论的操作
     *
     * @param activity
     */
    public void tipComment(Activity activity, Typeface iconfont, List<TipCommentBean> list, String id) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dilog_tip_show, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        TextView textCancel = view.findViewById(R.id.tip_btn_close);
        textCancel.setTypeface(iconfont);
        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        RecyclerView tip_list = view.findViewById(R.id.tip_list);
        tip_list.setLayoutManager(UIUtils.getRecyclerViewManager(false, activity));
        TipListAdapter tipListAdapter = new TipListAdapter(activity, list, iconfont);
        tip_list.setAdapter(tipListAdapter);
        tipListAdapter.OnItemClick(new TipListAdapter.OnItemClick() {
            @Override
            public void setOnItemClick(View view, int pos) {
                dialog.dismiss();
                Map<String, String> stringMap = new HashMap<>();
                stringMap.put("id", id);
                stringMap.put("content", list.get(pos).getValue());
                Api.getInstanceService(Constants.Ticket_URL).addTipComment(stringMap).enqueue(new BaseCallback<BaseJSON>() {
                    @Override
                    public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                        //举报成功的操作
                        BaseJSON baseJSON = new BaseJSON();
                        baseJSON.returnMessage = "举报成功";
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                EventBus.getDefault().post(baseJSON);
                            }
                        }, 100);
                    }
                });
            }
        });
    }


    /**
     * 显示输入评论信息的弹出框
     * item回复子项的点击
     */
    private String content = "";//输入框的信息

    public void showCommentDialog(Activity activity, ReplyContent item, ReplyContent commentBean) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_input_content, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);

        final EditText comment = view.findViewById(R.id.comment);
        final TextView noc = view.findViewById(R.id.noc);

        TextView cancel = view.findViewById(R.id.input_cancel);
        final Button ensure = (Button) view.findViewById(R.id.input_confirm);
        LinearLayout dia_log = (LinearLayout) view.findViewById(R.id.dia_log);

        if (item != null && commentBean != null) {
            String name = "@" + item.getUserName() + ":";
            String ht = "<font color='#108EE9'>" + name + "</font>" + activity.getResources().getString(R.string.input_hint);
            comment.setHint(Html.fromHtml(ht));
        } else if (commentBean != null && item == null) {
            String name = "@" + commentBean.getUserName() + ":";
            String ht = "<font color='#108EE9'>" + name + "</font>" + activity.getResources().getString(R.string.input_hint);
            comment.setHint(Html.fromHtml(ht));
        } else {
            comment.setHint(activity.getResources().getString(R.string.input_hint));
        }
        if (content != null && !content.equals("")) {
            comment.setText(content);
            comment.setSelection(content.length());
            noc.setText(content.length() + "/240");
            ensure.setTextColor(activity.getResources().getColor(R.color.main_color));
        }
        comment.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                noc.setText(comment.getText().toString().trim().length() + "/240");
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    ensure.setTextColor(activity.getResources().getColor(R.color.main_color));
                } else {
                    ensure.setTextColor(activity.getResources().getColor(R.color.text_b2));
                }
            }
        });
        ensure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //提交
                dialog.dismiss();
                if (comment.getText().toString().trim().length() < 10) {
//                    RxToast.info("评论内容请多于10个字");
                    ToastUtil.getToastEmail().ToastShow(activity, null, 1, R.layout.toast_view, activity.getResources().getString(R.string.opinion_msg));
                    comment.setText("");
                    content = "";
                    return;
                }
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
                }
                content = comment.getText().toString();
                Map<String, String> maps = new HashMap<>();
                if (item != null && commentBean != null) {//回复子评论
                    maps.put("type", "0");
                    maps.put("typeId", getid);
                    maps.put("content", content);
                    maps.put("mainCommentId", commentBean.getId() + "");
                    maps.put("replyType", "1");
                    maps.put("replyCommentId", item.getId() + "");
                    maps.put("replyUserId", item.getUserId() + "");
                    Api.getInstanceService(Constants.Ticket_URL).getAddReplyComment(maps).enqueue(new BaseCallback<BaseJSON>() {
                        @Override
                        public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                            //发布成功的信息互调
                            result.returnMessage = "发布成功";
                            comment.setText("");
                            content = "";
                            new Handler().postDelayed(new Runnable() {
                                public void run() {
                                    EventBus.getDefault().post(result);
                                }
                            }, 100);
                        }
                    });
                } else if (commentBean != null && item == null) {//回复主评论
                    maps.put("type", "0");
                    maps.put("typeId", getid);
                    maps.put("content", content);
                    maps.put("mainCommentId", commentBean.getId() + "");
                    maps.put("replyType", "0");
                    maps.put("replyCommentId", commentBean.getId() + "");
                    maps.put("replyUserId", commentBean.getUserId() + "");
                    Api.getInstanceService(Constants.Ticket_URL).getAddReplyComment(maps).enqueue(new BaseCallback<BaseJSON>() {
                        @Override
                        public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                            //发布成功的信息互调
                            result.returnMessage = "发布成功";
                            comment.setText("");
                            content = "";
                            new Handler().postDelayed(new Runnable() {
                                public void run() {
                                    EventBus.getDefault().post(result);
                                }
                            }, 100);
                        }
                    });
                } else {
                    maps.put("type", "0");
                    maps.put("typeId", "" + getid);
                    maps.put("content", content);
                    Api.getInstanceService(Constants.Ticket_URL).getaddComment(maps).enqueue(new BaseCallback<BaseJSON>() {
                        @Override
                        public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                            //发布成功的信息互调
                            result.returnMessage = "发布成功";
                            comment.setText("");
                            content = "";
                            new Handler().postDelayed(new Runnable() {
                                public void run() {
                                    EventBus.getDefault().post(result);
                                }
                            }, 100);
                        }
                    });
                }

            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //这里执行相应的删除代码
                dialog.dismiss();
                comment.setText("");
                content = "";
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
                }

            }
        });
        dialog.show();

        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
        window.getDecorView().setPadding(0, 0, 0, 0); //消除边距
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        if (dialog.isShowing()) {//显示软键盘
            activity.getWindow().getDecorView().postDelayed(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        comment.requestFocus();
                        imm.showSoftInput(comment, 0);
                    }
                }
            }, 100);
        }
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (!comment.getText().toString().equals("")) {
                    content = comment.getText().toString();
                }
            }
        });

    }
}
